// 测试哪些内存可以通过/dev/mem去映射

#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include <sys/mman.h>
#include <fstream>
#include <vector>
#include <algorithm>
#include <string>
#include <sstream>


int main(void)
{
    // 打开 /proc/iomem 文件
    std::ifstream file("/proc/iomem");
    if (!file.is_open()) {
        std::cerr << "Failed to open /proc/iomem" << std::endl;
        return 1;
    }

    std::vector<std::string> firstColumnValues; // 用于存储第一列的数据
    std::string line;

    // 逐行读取文件内容
    while (std::getline(file, line)) {
        std::istringstream iss(line);
        std::string firstColumn;

        // 提取第一列数据（即 "-" 前面的部分）
        if (std::getline(iss, firstColumn, '-')) {
            // 去掉可能的空格
            firstColumn.erase(std::remove(firstColumn.begin(), firstColumn.end(), ' '), firstColumn.end());
            firstColumnValues.push_back(firstColumn);
        }
    }

    // 关闭文件
    file.close();

    int fd = open("/dev/mem", O_RDWR);
    if (fd < 0) {
        std::cerr << "Failed to open /dev/mem" << std::endl;
        return 1;
    }
    // 遍历第一列数据，尝试映射内存
    std::cout<< std::hex << std::showbase;
    for (auto& firstColumnValue : firstColumnValues) {
        unsigned long physaddr = std::stoull(firstColumnValue, nullptr, 16);
        void* ptr = mmap(NULL, 0x1000, PROT_READ, MAP_SHARED, fd, physaddr);
        
        if (ptr == MAP_FAILED) {
            std::cout << physaddr << " failed to map" << std::endl;
        }
        else {
            std::cout << physaddr << " mapped successfully" << std::endl;
            munmap(ptr, 0x1000);
        }
    }
    close(fd);
}